import { getRoleAndProject } from '@/api/qss/index.js'
import { getEncryptedStr } from '@/utils/index.js'

// 获取用户信息
export function getUserInfo() {
    const phone = uni.getStorageSync('phone');
    return getRoleAndProject({ phone: phone}).then(res => {
            if (res.code === 200 && res.data) {
                const { data } = res;
                
                // 处理项目数据
                const { activeProject, projects } = processProjects(data);
                
                //获取已有激活项目
                if( uni.getStorageSync('activeProject')){
                    const activeProjectId = uni.getStorageSync('activeProject').id
                    //判断activeProjectId是否在projects中 不在存储最新项目信息
                    const isExist = projects.some(item => item.id === activeProjectId);
                    if (!isExist) {
                        uni.setStorageSync('activeProject', activeProject);
                    }
                }else{
                    uni.setStorageSync('activeProject', activeProject);
                }
                uni.setStorageSync('projects', projects);


                // 构建用户信息对象
                const role = uni.getStorageSync('activeProject')?.role || '普通人员';
                const userInfo = buildUserInfo(data);

                uni.setStorageSync('userInfo', {...userInfo, role });

                // 获取加密字符串
                getEncryptedStr();

                return Promise.resolve(res);
            }else{
                return Promise.reject('获取用户信息失败');
            }
        })
        .catch(error => {
            console.error('getUserInfo 执行失败:', error);
            return Promise.reject(error);
        })
}



// 构建用户信息辅助函数
function buildUserInfo(data) {
    return {
        role: data.role,
        idCard: data.idCard,
        name: data.name,
        sex: data.sex,
        avatar: data.avatar?`${data.avatar}?Authorization=Bearer ${uni.getStorageSync('token')}&platform=corp`: '',
        postName: data?.postName,
        enterprise: data?.enterprise,
        phonenumber: data?.phonenumber
    };
}

// 处理项目数据辅助函数
// 处理项目数据
function processProjects(data) {
    // 定义一个空数组，用于存储项目
    const projects = [];
    // 定义一个空变量，用于存储当前活动项目
    let activeProject = null;
    
    // 处理管理人员项目
    if (data.projects?.length > 0) {
        if (data.role === '管理人员' && !activeProject) {
            activeProject = data.projects[0];
            activeProject.role = '管理人员'
        }
        
        projects.push(...data.projects.map(item => ({
            id: item.id,
            flagAdmin: true,
            flagProject: false
        })));
    }
    
    // 处理从业人员项目
    if (data.projects1?.length > 0) {
        if (data.role === '从业人员' && !activeProject) {
            activeProject = data.projects1[0];
            activeProject.role = '从业人员'
        }
        
        projects.push(...data.projects1.map(item => ({
            id: item.id,
            flagAdmin: false,
            flagProject: false
        })));
    }
    
    return { activeProject, projects };
}
